<template>
<div class="order-details">
    <div class="order" v-if="order">
        <div class="order-nav">
            <a href="buyPayList.php"><img src="./img/vector.png" alt="" /></a>
            <span>订单已支付</span>
        </div>
        <div class="order-info box">
            <div class="top">
                <img class="left" src="./img/head_sculpture.png" alt="" />
                <div class="right">
                    <p class="name">店铺授权服务</p>
                    <p class="details">
                        <span>{{order.pid == 2?'美团':'饿了么'}}外卖平台店铺授权服务</span>
                    </p>
                </div>
            </div>
            <div class="details">
                <span>{{order.buy_month}}个月店铺授权服务</span>
                <div class="nums">
                    <span>x1</span>
                    <span>¥{{ order.money }}</span>
                </div>
            </div>
            <p class="pay-amount">
                <span>实付金额</span>
                <span class="price">¥{{ order.money }}</span>
            </p>
        </div>
        <div class="order-refund box" v-if="order.refund_money !=0 && order.refund_info&&order.refund_info.status == 1">
            <p>退款：{{order.refund_money}}元</p>
            <p>退款成功 <img src="./img/b_right.png" alt=""></p>
        </div>
        <div class="order-service box">
            <p class="title">服务包含内容</p>
            <ul>
                <li>
                    <div class="name">店铺授权有效期{{order.buy_month}}个月（仅供一个店铺使用）</div>
                    <div class="nums" v-if="order.shop_name">
                        <span>x1</span><span :class="order.is_refund == 1?'not':'green'">{{order.is_refund == 1? '已失效':'已生效'}}</span>
                    </div>
                    <div class="nums" v-else>
                        <span>x1</span><span class="not">未生效</span>
                    </div>
                </li>
                <!-- <li v-if="order.sn>0">
                    <div class="name">{{order.service_type == 1? '备用机服务':'保修服务'}} 打印机：{{ order.sn }}</div>
                    <div class="nums">
                        <span>x1</span><span :class="order.is_refund == 1?'not':'green'">{{order.is_refund == 1? '已失效':'已生效'}}</span>
                    </div>
                </li>
                <li v-else>
                    <div class="name">硬件套餐：打印机保修服务 <span class="set" @click="selectMeal()">去应用></span></div>
                    <div class="nums">
                        <span>x1</span><span class="yellow">未生效</span>
                    </div>
                </li> -->
                <li v-if="order.prod_id==3 || order.prod_id==4">
                    <div class="name">12个月{{order.prod_id==3?'2G':'4G'}}流量卡充值 打印机：{{order.sim_sn}}</div>
                    <div class="nums">
                        <span>x1</span><span class="green">已充值</span>
                    </div>
                </li>
                <!-- <li>
                    <div class="name">店铺置休</div>
                    <div class="nums">
                        <span>x1</span><span :class="order.is_refund == 1?'not':'green'">{{order.is_refund == 1? '已失效':'已生效'}}</span>
                    </div>
                </li> -->
            </ul>
        </div>
        <div class="order-status box">
            <div class="title">服务状态</div>
            <p>
                <span class="left">订单号</span><span class="right">{{ order.id }}</span>
            </p>
            <p>
                <span class="left">微信支付单号</span><span class="right">{{ order.pay_order_no }}</span>
            </p>
            <p>
                <span class="left">支付方式</span><span class="right">微信支付</span>
            </p>
            <p>
                <span class="left">下单时间</span><span class="right">{{ order.created_at | formatDate }}</span>
            </p>
        </div>
        <div class="order-btn" v-if="(!order.third_shopid&&!order.refund_info)||(order.refund_info&&order.refund_info.status == 2)" @click="applyRefund()">申请退款</div>
    </div>
    <!-- loading组件 -->
    <loading v-if="isLoading"></loading>
    <!-- 设置套餐服务 -->
    <div class="setMeal" v-if="setMealType">
        <div class="content">
            <img class="content-close" @click="closeSetMeal()" src="./img/close.png" alt="" />
            <div class="top height">
                <p class="title">您有已购订单未选用硬件服务</p>
            </div>
            <div class="other">
                <div class="center">
                    <div class="once">
                        <div :class="['input',{'error':errorType==1}]">
                            <input class="it" type="text" placeholder="输入打印机编号 (打印机底部标贴可查)" maxlength="10" @input="handOnceSn()" v-model="serviceSn" @click.stop="showSnList()" oninput="value=value.replace(/[^\d]/g,'')">
                            <em v-if="errorType==1">{{errorText}}</em>
                            <div class="select-menu" v-if="snList.length>0 && snListStatus">
                                <p v-for="item in snList" :key="item.id" @click.stop="selectSn(item)">
                                    {{ item.sn }}
                                </p>
                            </div>
                            <div class="loading" v-show="!requestBan">
                                查询中
                                <van-loading color="#999" size="20" />
                            </div>
                        </div>
                        <div class="meal">
                            <div :class="['item', { active: _item.checked },{not:_item.id == 2 && exceeding}]" v-for="(_item, index) in snTypeList" :key="_item.id" @click="selectSnType(_item)">
                                <img class="left" :src="require(`./img/icon_${index+1}.png`)" alt="" />
                                <div class="right">
                                    <p>{{ _item.name }}</p>
                                </div>
                            </div>
                            <div class="error-text" v-if="errorType==2">{{ errorText }}</div>
                        </div>
                    </div>
                    <div class="service-content">
                        <p>1、本服务仅支持一台打印机可享，请谨慎填写，一经确定，不可修改。</p>
                        <p>2、本服务以所属套餐成功绑定店铺时开始生效，请及时选择套餐以免造成不必要的损失。</p>
                        <p>3、一台打印机最多可获取保修期1年。</p>
                        <p>4、打印机服务：赠送保修期 <span @click="viewServices(2)">(查看服务详情)</span></p>
                    </div>
                </div>
            </div>
            <div class="bottom">
                <div class="btn" @click="confirmMeal()">确定</div>
            </div>
        </div>
    </div>
    <Dialog v-if="isDialog" @confirm="confirm" @close="close" :config="dialogConfig"></Dialog>
</div>
</template>

<script>
import loading from "@com/loading/index.vue";
import {
    getRequest,
    apiUrl,
    FormatDateTimes,
    yearFormatDate
} from "@util/index";
import request from "@util/request";
import qs from "qs";
import Dialog from "@com/Dialog/index.vue";
import {
    Toast
} from 'vant';
export default {
    data() {
        return {
            pid: 2,
            order: false,
            param: {},
            isLoading: false,
            setMealType: false,
            errorType: null,
            serviceSn: "",
            errorText: "",
            snList: [],
            snListStatus: false,
            requestBan: true,
            exceeding: false, //是否可点击延长保修服务
            serviceType: null,
            isDialog: false,
            dialogConfig: null,
            limit: true,
            snListRequest: true,
            snTypeList: [{
                name: "保修服务（赠送打印机6个保修服务）",
                checked: false,
                id: 2,
            }],
            closeSetMealPop: false,
            clickSnItem: {},
            dialogType: false, //1=>申请退款
        };
    },
    filters: {
        formatDate: function (value) {
            return FormatDateTimes(parseInt(value), 0)
        }
    },
    components: {
        loading,
        Dialog
    },
    methods: {
        applyRefund() {
            this.isDialog = true;
            this.dialogConfig = {
                title: "您的服务还未激活使用，确定要申请退款吗？",
                confirm: "确定",
                cancel: "取消"
            };
            this.dialogType = true
        },
        closeSetMeal() {
            if (this.serviceSn != '' && this.serviceType != null) {
                this.isDialog = true;
                this.dialogConfig = {
                    title: "关闭弹窗将不保存已填写信息，确认关闭？",
                    confirm: "确定",
                    cancel: "取消"
                };
                this.closeSetMealPop = true
                return
            }
            this.setMealType = null
            this.serviceSn = ""
            this.serviceType = null
            this.snTypeList[0].checked = false
            this.exceeding = false
            this.errorText = ""
            this.errorType = null
        },
        // 单个选用---手动输入sn的逻辑
        handOnceSn() {
            this.snListStatus = false
            if (this.serviceSn.length > 8) {
                // 输入的sn与sn列表相同时
                if (this.snList.some(i => i.sn === this.serviceSn)) {
                    this.errorText = ""
                    this.exceeding = false
                    this.errorType = null
                    this.serviceType = null
                    this.snTypeList.map((i) => {
                        i.checked = false
                    })
                    let currentSn = this.snList.filter(i => i.sn == this.serviceSn)[0]
                    if (this.out_date(currentSn.expire_time) || (currentSn.stat_month + +this.order.repair_month > 12)) {
                        this.exceeding = true
                    } else {
                        this.exceeding = false
                    }
                } else {
                    if (this.requestBan) {
                        this.requestBan = false
                        request({
                            method: "POST",
                            url: apiUrl,
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                            },
                            data: {
                                action: "ShopService_isExtendWarranty",
                                sn: this.serviceSn,
                            },
                            transformRequest: [
                                function (data) {
                                    return qs.stringify(data);
                                },
                            ],
                        }).then(res => {
                            this.requestBan = true
                            let data = res.data.data
                            if (data.expire_time == 0 || data.stat_month >= 12) {
                                this.errorType = 1
                                this.errorText = "您输入的打印机暂未绑定激活，请先绑定激活打印机。"
                                this.exceeding = true
                            } else {
                                this.errorText = ""
                                this.exceeding = false
                                this.errorType = null
                            }
                        })
                    }
                }

            }
        },
        // 获取sn列表
        initSnList() {
            let data = {
                method: "POST",
                url: apiUrl,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                data: {
                    action: "ShopService_getPrintListByUid",
                },
                transformRequest: [
                    function (data) {
                        return qs.stringify(data);
                    },
                ],
            };
            request(data).then((res) => {
                let _data = res.data;
                if (_data.ret == 0) {
                    this.snList = _data.data
                    this.snList.map(item => {
                        item.type = "sn"
                    })
                }
            });
            this.$nextTick(() => {
                document.addEventListener("click", (e) => {
                    if (!e.target.classList.contains("it")) {
                        this.snListStatus = false
                    }
                });
            });
        },
        // 是否展示打印机列表
        showSnList() {
            this.errorText = '';
            this.errorType = null
            this.snListStatus = !this.snListStatus;
            if (this.snListRequest) {
                this.snListRequest = false
                this.initSnList()
            }
        },
        // 选择打印机
        selectSn(item) {
            this.clickSnItem = item
            this.serviceSn = item.sn
            this.snListStatus = false
            this.serviceType = null
            this.snTypeList.map((i) => {
                i.checked = false
            })
            if (this.out_date(item.expire_time) || (+item.stat_month + +this.order.repair_month > 12)) {
                this.exceeding = true
            } else {
                this.exceeding = false
            }
            // 订单时间减去打印机时间一年内也可以选择延保服务
            if (this.out_date(item.expire_time)) {
                if (+this.order.created_at - +item.first_bind_time <= yearFormatDate() && (+item.stat_month + +this.order.repair_month <= 12)) {
                    this.exceeding = false
                }
            }
        },
        // 选择套餐类型
        selectSnType(item) {
            //  单个订单，当延长保修时间超过24小时时不能点击
            if (this.exceeding && item.id == 2) {
                return
            }
            this.snTypeList.map((i) => {
                if (i.id == item.id) {
                    i.checked = true;
                } else {
                    i.checked = false;
                }
            });
            this.serviceType = item.id
            this.errorType = null
        },
        // 已过期
        out_date(time) {
            let currenttime = parseInt(new Date().getTime() / 1000);
            if (time == 0) {
                return true
            }
            if (+time < currenttime) {
                return true;
            }
            return false
        },
        // 说明
        viewServices() {
            this.isDialog = true;
            let kg = "&nbsp;&nbsp;&nbsp;&nbsp;"
            this.dialogConfig = {
                title: "赠送保修期",
                details: `
                    <p>${kg}购买一次店铺授权服务可获得一次赠送的增加打印机保修时长套餐的服务，赠送的保修时长服务在对应店铺授权服务有效期内有效；</p>
                    <p>例：购买1年套餐则对应获得为单台打印机增加保修时长6个月赠送服务；</p>
                    <p>${kg}打印机赠送保修服务有效期以所属套餐成功授权店铺起计算开始时间。请在所属套餐授权有效期内6个月前，尽快提交服务所享打印机编号；授权有效期过期，则该赠送服务将自动失效。</p>
                    <p>例：若您在2022年1月1日购买店铺授权服务并成功授权店铺，则赠送保修时长服务有效时间为2022年1月1日到2022年6月1日。</p>
                    <p>${kg}若在购买后未及时设置，则可在 “ 平台店铺管理列表 - 店铺信息卡片 - 硬件服务 ” 或 “ 我的 - 购买记录 - 对应订单详情页 - 硬件套餐：打印机保修服务 -去应用 ” 去进行提交。</p>
                    <p>${kg}您的打印机必须在打印机首次激活时间到购买店铺授权服务的时间之间的间隔不超过2年时间。</p>
                    <p>${kg}若购买多次店铺授权，并选择本服务，您可选择对不同的打印机设置添加保修时长，或对单台打印机叠加保修时长。一台打印机最多可享受12个月保修时长。</p>
                    <p>${kg}若您对保修服务申请了退款，则打印机保修服务时长将根据退款内容对应缩减。</p>
                    <p class='red'>* 注：本服务为购买授权店铺套餐的附赠服务，非付费服务。</p>`,
                confirm: "知道了",
            };
        },
        confirm() {
            this.isDialog = false
            if (this.dialogType) {
                location.href = `buyApplyRefund.php?id=${this.order.id}`
            }
            if (this.closeSetMealPop) {
                this.setMealType = null
                this.serviceSn = ""
                this.serviceType = null
                this.snTypeList[0].checked = false
                this.closeSetMealPop = false
            }
            this.errorText = ""
            this.errorType = null
        },
        close() {
            this.isDialog = false;
            this.closeSetMealPop = false
        },
        //验证数据
        verification() {
            if (this.serviceSn == '' || !(/^\d{9,10}/.test(this.serviceSn))) {
                this.errorText = "打印机编号输入错误"
                this.errorType = 1
                return false
            }
            if (+this.clickSnItem.stat_month + +this.order.repair_month > 12) {
                this.errorType = 2
                this.errorText = "此打印机延长保修已超12个月，不再享受延长保修;"
                return false
            }
            if (this.out_date(this.clickSnItem.expire_time)) {
                if (+this.order.created_at - +this.clickSnItem.first_bind_time > yearFormatDate()) {
                    this.errorType = 2
                    this.errorText = "此打印机使用超过2年，不可享受延长保修;"
                    return false
                }
            }
            if (this.serviceType == null) {
                this.errorType = 2
                this.errorText = "请选择打印机服务套餐"
                return false
            }
            return true
        },
        // 确定选择服务按钮
        confirmMeal() {
            if (!this.verification()) return
            let params = {
                action: "ShopService_setSnServiceType",
                content: JSON.stringify([{
                    orderId: this.order.id,
                    sn: this.serviceSn,
                    service_type: this.serviceType
                }]),
                pid: this.pid,
                third_id: this.order.third_shopid
            }
            if (this.limit) {
                this.limit = false
                request({
                    method: "POST",
                    url: apiUrl,
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    data: params,
                    transformRequest: [
                        function (data) {
                            return qs.stringify(data);
                        },
                    ],
                }).then((res) => {
                    if (res.data.ret == 0) {
                        Toast({
                            message: '设置硬件套餐成功！',
                            position: 'top',
                            onClose: () => {
                                this.setMealType = null
                                this.limit = true
                                this.initPage()
                            }
                        })
                    } else {
                        this.limit = true
                        Toast({
                            message: res.data.msg,
                            position: 'top',
                        })
                    }
                });
            }
        },
        // 打开服务请求弹窗
        selectMeal() {
            this.setMealType = true
        },
        initPage() {
            let data = {}
            let that = this
            data.action = "ShopService_getOrderDetail"
            data.id = this.param.id
            this.isLoading = true
            request({
                method: "POST",
                url: apiUrl,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                data: data,
                transformRequest: [
                    function (data) {
                        return qs.stringify(data);
                    },
                ],
            }).then((res) => {
                this.isLoading = false
                let data = res.data.data;
                that.order = data
            });
        }
    },
    created() {
        this.param = getRequest()
        this.initPage()
    },
};
</script>

<style lang="less">
@import "index.less";
</style>
